import { ref } from 'vue'
import OSS from 'ali-oss'

export default function () {
  const client = ref(null)
  const ossInfo = ref()
  // 获取并生成oss相关配置
  const getOssInfo = async () => {
    try {
      const res = await $request.get('/api/common/oss_token/query')
      if (res) {
        ossInfo.value = res
        // 配置 OSS 客户端
        client.value = new OSS({
          // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
          region: 'oss-cn-hangzhou',
          // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
          accessKeyId: res?.accessKeyId,
          accessKeySecret: 'T56ooMHfYSqQlMEt18OuWS6dXUYoZP',
          // 填写Bucket名称，例如examplebucket。
          bucket: 'zkkj-hz',
          key: res?.dir,
        })
      }
    } catch (error) {}
  }
  const uploadFile = ({ file }) => {
    return new Promise(async (resolve, reject) => {
      if (!client.value || !ossInfo.value) {
        await getOssInfo()
      }
      // 生成文件名: 4位包含0-9数字及a-z字母的随机字符串
      let fileName = `${file.name.substr(0, file.name.lastIndexOf('.')).toLowerCase()}_${Array.from(Array(4), () => Math.floor(Math.random() * 36).toString(36)).join('')}`
      // 获取文件扩展名
      const extName = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase()
      const key = ossInfo.value?.dir || ''
      // 获取文件信息
      const urlInfo = await client.value.put(`${key}${fileName}.${extName}`, file)
      resolve({
        name: `${fileName}.${extName}`,
        size: file.size,
        type: file.type,
        uid: file.uid,
        url: urlInfo.url,
        status: 200,
      })
    })
  }
  const deleteFile = ({ file }) => {
    return new Promise(async (resolve, reject) => {
      if (!client.value || !ossInfo.value) {
        await getOssInfo()
      }
      const key = ossInfo.value?.dir || ''
      client.value.delete(`${key}${file}`)
      resolve(true)
    })
  }
  return { uploadFile, deleteFile }
}
